/*
 * chat_file.c
 *
 *  Created on: 2012-9-6
 *      Author: rendong
 */

#include <aio.h>
#include "chat_file.h"


/**
 * 写入文件
 */
void chat_file_write(int fd, void *buf, int nbytes)
{
	struct aiocb *myaiocb;

	myaiocb = (struct aiocb *)malloc(sizeof(struct aiocb));
	memset(myaiocb , 0x0 , sizeof(struct aiocb));

	myaiocb->aio_fildes = fd;
	myaiocb->aio_buf = buf;
	myaiocb->aio_nbytes = nbytes;
	myaiocb->aio_offset = O_APPEND;

	// 采用线程通知，信号通知有未知错误,会导致程序卡住
	myaiocb->aio_sigevent.sigev_notify = SIGEV_THREAD;//SIGEV_SIGNAL;
	myaiocb->aio_sigevent.sigev_notify_function = chat_file_handler;
	myaiocb->aio_sigevent.sigev_notify_attributes = NULL;

	myaiocb->aio_sigevent.sigev_value.sival_ptr = myaiocb;

	if (aio_write(myaiocb) != 0){
		chat_log_error("aio_write error:%d %s\n", errno, strerror);
	}
}


/**
 * 内存释放
 */
void chat_file_handler( sigval_t sigval)
{
	struct aiocb *req;

	req = (struct aiocb *)sigval.sival_ptr;

	if (req != NULL)
	{
		//buff = req->aio_buf;
		free((void *)req->aio_buf);

		free(req);
	}
}
